package com.example.shirodemo.config.thymeleaf;

import static org.thymeleaf.standard.processor.StandardWithTagProcessor.PRECEDENCE;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @author 绫小路
 * @date 2021/1/14 23:02
 * @description
 */
public class AuthTagProcessor extends AbstractAttributeTagProcessor {

  private static final String SHIRO = "shiro";

  public AuthTagProcessor(String dialectPrefix) {
    super(
        TemplateMode.HTML, // This processor will apply only to HTML mode
        dialectPrefix,     // Prefix to be applied to name for matching 前缀
        null,              // No tag name: match any tag name
        false,             // No prefix to be applied to tag name
        SHIRO,         // Name of the attribute that will be matched
        true,              // Apply dialect prefix to attribute name
        PRECEDENCE,        // Precedence (inside dialect's own precedence)优先级
        true);             // Remove the matched attribute afterwards
//    super( TemplateMode.HTML, dialectPrefix, elementName, prefixElementName, isAuthenticated, prefixAttributeName, precedence, removeAttribute);
  }

  @Override
  protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, String attributeValue,
      IElementTagStructureHandler structureHandler) {
    Subject subject = SecurityUtils.getSubject();
    if ("isAuthenticated".equals(attributeValue)) {//判断是否登录
      if (!subject.isAuthenticated()) {
        structureHandler.removeElement();//未登录时将元素移除  例如<a href="/admin" th:shiro="isAuthenticated">admin</a>
      }
    }
  }
}
